var express = require('express')
var router = express.Router()
var formidable = require('formidable')
let path = require('path')
let url = require('url')

/**
 * 文件上传
 * @route POST /fileUpload
 * @summary 文件上传
 * @group 文件上传 - 文件上传到服务器
 * @consumes multipart/form-data
 * @produces application/json application/xml
 * @headers {string} 200.X-Expires-After - 	date in UTC when token expires
 * @param  {array} username.body - 
 * @returns {Response.model} 200 - 
 * @returns {Error}  default - Unexpected error
 * @security JWT
 */
router.post('/fileUpload', function (req, res, next) {
    const HOST = req.headers.host
    res.setHeader('Content-Type', 'multipart/form-data')
    let form = formidable({ multiples: true })
    form.encoding = 'utf-8' // 编码
    // 保留扩展名
    form.keepExtensions = true
    //文件存储路径 最后要注意加 '/' 否则会被存在public下
    let imgFilePath = path.join(__dirname, '../public/images')
    form.uploadDir = imgFilePath
    // 解析 formData 数据
    form.parse(req, (err, fields, files) => {
        if (err) return next(err)
        if (files.file == undefined) {
            res.json({ "code": 500, "data": "", "msg": "请上传图片" })
        }
        let imgPath = files.file.path
        let imgName = files.file.name
        let pathArr = imgPath.split("\\")
        imgPath = pathArr[pathArr.length - 2] + "/" + pathArr[pathArr.length - 1]
        res.json({ "code": 200, "data": { name: imgName, path: HOST + "/" + imgPath }, "msg": "上传图片成功" })
    })
})

module.exports = router